<template>
  <section class="component enclosure-step">
    <el-form v-if="isShow" :model="formData" :page="pageService" ref="enclosure-step-form" label-width="100px">
      <el-form-item label="附件名称" prop="name">
        <file-upload :disabled="isDetail" :fileList.sync="fileList" :showFileList="true" :AllowExtension="['avi','mp4','wmv','jpeg','JPEG','jpg','png','pdf','word','doc','docx','excel','xls','xlsx']" :buttonName="'选择文件'" @onUploadRemove="onUploadRemove" @onUploadSuccess="onUploadSuccess">
        </file-upload>
      </el-form-item>
      <el-form-item label="附件备注：" prop="fileRemark">
        <el-input :disabled="isDetail" type="textarea" v-model="formData.fileRemark" maxlength="200" show-word-limit></el-input>
      </el-form-item>
    </el-form>
    <div class="text-center">
      <el-button @click="previousStepEmit">上一步</el-button>
      <el-button v-if="isShow" @click="deleteFiles">取消</el-button>
      <el-button v-if="isShow" @click="submit" :loading="submitLoading">上传</el-button>
    </div>
    <data-box :data="dataSet" :height="200" class="annex-info-data-box" @onPageChange="showLegalInfoById" :page="pageService">
      <template slot="columns">
        <el-table-column prop="fileName" label="附件名称" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="fileRemark" label="附件备注" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="createTime" label="上传时间" :formatter="(row) => $filter.dateTimeFormat(row.createTime)" :min-width="$helper.getColumnWidth(5)">
        </el-table-column>
        <el-table-column prop="operatorRealName" label="上传人" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column label="操作" :min-width="$helper.getOperateWidth(2)">
          <template slot-scope="scope">
            <!-- <el-button type="text">
              <el-image style="width:50px;height:50px;margin-top:10px" :src="scope.row.fileUrl" placeholder="预览" :preview-src-list="srcList">
              </el-image>
            </el-button> -->
            <el-button :disabled="isDetail" type="text" @click="$common.downloadFile(scope.row.fileUrl,scope.row.fileName)" class="btn download">下载</el-button>
            <el-button :disabled="isDetail" @click="onClickDelete(scope.row.id)" type="text">删除</el-button>
          </template>
        </el-table-column>
      </template>
    </data-box>

  </section>
</template>
<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
import DataBox from '~/components/common/data-box.vue'
import FileUpload from '~/components/common/file-upload.vue'
import { Prop, Emit } from "vue-property-decorator";
import { Dependencies } from '~/core/decorator';
import { PageService } from "~/utils/page.service";
import { SortService } from "~/utils/sort.service"
import { CaseOperatorPageService } from '~/services/domain-service/case-operator-page.service';
import { FileUploadService } from "~/services/file-service/file-upload.service"
import { State, Action, Getter, namespace } from "vuex-class";
import { MENU_CHANNEL } from "~/config/enum.config";
import { CaseLegalRecordService } from '~/services/domain-service/case-legalRecord.service';
const CollectionExecutionModule = namespace('collection-execution');
@Component({
  components: {
    DataBox,
    FileUpload
  }
})

export default class EnclosureStep extends Vue {
  @Dependencies(CaseOperatorPageService) private caseOperatorPageService: CaseOperatorPageService;
  @Dependencies(FileUploadService) private fileUploadService: FileUploadService;
  @Dependencies(CaseLegalRecordService) private caseLegalRecordService: CaseLegalRecordService;
  @CollectionExecutionModule.State private caseId;
  @CollectionExecutionModule.State private menuChannel;
  @CollectionExecutionModule.State private otherData;
  @CollectionExecutionModule.Mutation private updateCurrentSavedStep;

  @Prop({ type: String, required: false }) private id;
  @Prop({ type: String }) private operatorId;
  @Prop({ type: Boolean }) private isDetail;
  @Dependencies(PageService) private pageService: PageService;
  @Dependencies(SortService) private sortService: SortService;
  @State private userData
  private fileList: any = []
  private formData: any = {
    legalStage: "FILE",
    legalStatus: "FILE",
    fileRemark: "",
    id: "",
    fileIds: []
  }
  private dataSet: any = []
  private submitLoading: boolean = false
  private srcList: string[] = []
  private fileUploadRes: any = {}

  private get isShow () {
    const arr = [MENU_CHANNEL.Legal_personal, MENU_CHANNEL.Legal_team, MENU_CHANNEL.Assist_legal]
    if (arr.find(v => this.menuChannel === v)) {
      // 添加催记显示保存按钮 或编辑催记 与该登录用户一致显示
      if (!this.operatorId || this.operatorId === this.userData.id) return true
      else return false
    }
    return false
  }
  @Emit('previousStep') private previousStepEmit () { }

  @Emit('emitSuccess')
  private emitSuccess () {
    if (this.id) {
      this.showLegalInfoById();
    } else {
      // this.showLegalInfo();
    }
  }
  private onClickDowload (row) { }

  private mounted () {
    if (this.caseId) {
      this.showLegalInfoById();
    } else {
      // this.showLegalInfo();
    }
  }
  private showLegalInfo () {
    //查询上一条催记是否结案，回显数据
    // this.caseOperatorPageService
    //   .queryUnClossCaseLegalRecord(this.caseId)
    // const params = { "caseId": this.caseId }
    // this.caseLegalRecordService.addCaseLegalRecord(params)
    //   .subscribe(
    //     (data) => {
    //       if (data) {
    //         this.dataSet = data.legalFiles
    //         this.formData.id = data.id;
    //         this.dataSet.forEach(item =>{
    //           this.srcList.push(item.fileUrl)
    //         })
    //       }
    //     },
    //     (err) => {},
    //   );
  }

  // 列表详情
  private showLegalInfoById () {
    // const vals = { "caseId": this.caseId, "caseLegalRecordId": this.$store.state.DataCaseIdFlag }
    const vals = { "caseId": this.caseId }
    // const vals = { "caseLegalRecordId": this.$store.state.DataCaseIdFlag }
    this.caseLegalRecordService
      .getCaseLegalRecordFileByCaseId(vals, this.pageService)
      .subscribe((data) => {
        if (data) {
          this.formData.id = data.id;
          // this.formData.fileRemark = data.fileRemark;
          // this.dataSet = data.legalFiles

          this.dataSet = data
          this.dataSet.forEach(item => {
            this.srcList.push(item.fileUrl)
          })
          // this.pageService.total = data.length
        }
      },
        (err) => { },
      );
  }

  private onUploadSuccess (id, data) {
    console.log('onUploadSuccess', data);
    this.fileUploadRes = data
  }

  private setCurrentFormDataVal (step) {
    this.updateCurrentSavedStep(step)
    sessionStorage.setItem('currentFormDataVal', JSON.stringify(this.formData))
    setTimeout(() => {
      this.formData = JSON.parse(sessionStorage.getItem('currentFormDataVal') || "") || {}
    }, 300);
  }

  private async submit () {
    // console.log('this.caseId', this.caseId);
    // console.log('this.forData', this.formData);
    // console.log('this.id', this.id);
    this.fileList.forEach(element => {
      if (element.response) {
        const file: any = {}
        if (this.formData.id) {
          file.legalId = this.formData.id;
        }
        file.fileId = element.response.id;
        file.fileName = element.response.originalName;
        file.fileRemark = this.formData.fileRemark;
        file.fileUrl = element.response.url;
        this.formData.fileIds.push(file);
      }
    });

    if (this.menuChannel === MENU_CHANNEL.Assist_legal) {
      this.formData.assistId = this.otherData.assistId;
    }
    if (this.formData.fileIds.length > 0) {
      this.formData.caseId = this.caseId;
      // this.formData.caseLegalRecordId = this.caseId;
      // this.formData.caseInfoRecordId = this.caseId;
      const form: any = this.$refs["enclosure-step-form"];

      console.log('我要看formData数据：', this.formData);

      if (this.caseId && this.id) {
        this.setCurrentFormDataVal(4)
        this.caseLegalRecordService.editCaseLegalRecord(this.formData).subscribe(
          (data) => {
            form.resetFields();
            this.formData.id = "";
            this.emitSuccess();
            this.$message.success('法催催记立案已修改成功');
          },
          (err) => {
            this.submitLoading = false;
          },
        );
      } else {

        // 批量上传
        for (const v of this.formData.fileIds) {
          await this.caseLegalRecordService.editCaseLegalRecord({
            caseId: this.caseId,
            caseLegalRecordId: this.$store.state.DataCaseIdFlag,
            fileName: v.fileName,
            fileUrl: v.fileUrl,
            fileRemark: v.fileRemark,
            legalStage: 'FILE'
          }).subscribe()
        }
        
        this.setCurrentFormDataVal(4)

        //上传文件接口响应有延迟，通过定时器延缓
        setTimeout(() => {
          this.showLegalInfoById()

        }, 200);

        // const editParams = {
        //   caseId: this.caseId,
        //   caseLegalRecordId: this.$store.state.DataCaseIdFlag, fileName: this.fileUploadRes.fileName, fileUrl: this.fileUploadRes.url,
        //   fileRemark: this.formData.fileRemark,
        //   legalStage: 'FILE'
        // }
        // this.caseLegalRecordService.editCaseLegalRecord(editParams).subscribe(editRes => {
        //   console.log('editRes', editRes);
        //   this.caseLegalRecordService
        //     // .getCaseLegalRecordFileById({ "caseLegalRecordId": this.$store.state.DataCaseIdFlag })
        //     .getCaseLegalRecordFileByCaseId({ "caseId": this.caseId })
        //     .subscribe((data) => {
        //       console.log('data', data);
        //       this.dataSet = data
        //       this.dataSet.forEach(item => {
        //         this.srcList.push(item.fileUrl)
        //       })
        //     })
        // })
      }
    }
  }

  private onUploadRemove (file, fileList) {
    this.fileList = fileList
  }
  private deleteFiles () {
    this.fileList = []
    this.formData.fileIds = []
    this.formData.fileRemark = ''
  }

  /**
   * 删除
   */
  private onClickDelete (id) {
    const val = { "caseLegalRecordFileId": id }
    this.caseLegalRecordService.caseLegalRecordFile(val).subscribe(
      data => {
        this.$message.success("删除成功!");
        this.showLegalInfoById();
      })
  }
}

</script>

<style scoped>
.download {
  top: 0 !important;
}
</style>